package atom.core3.hibernate.spring.dao.impl;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.transform.Transformers;
import org.hibernate.type.Type;
import org.hibernate.type.TypeResolver;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.util.StringUtils;

import atom.core0.exception.BizException;
import atom.core0.j2ee.page.Page;
import atom.core0.j2ee.page.PageResult;
import atom.core1.object.CopyUtil;
import atom.core3.hibernate.TypeConvert;
import atom.core3.hibernate.jpa.AnnotationUtil;
import atom.core3.hibernate.jpa.DBAnnotation;
import atom.core3.hibernate.jpa.DBAnnotationManager;
import atom.core3.hibernate.jpa.DBFieldAnnotation;
import atom.core3.hibernate.util.QueryHelper;

/**
 * @author zhaomc 
 * 
 */
@SuppressWarnings("unchecked")
public abstract class BaseSpringHibernateDao extends HibernateDaoSupport  {
	private static Logger logger = Logger.getLogger("BaseDaoHibernateImpl");

	/**
	 * for override.
	 * 
	 * @return
	 */
	/*
	 * protected Class getModelClass() { return null; }
	 */
	abstract protected Class getModelClass();

	/**
	 * 清理session.
	 */
	public void clear() {
		
		this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				session.clear();
				return null;
			}
		});
	}

	public void flush() {
		this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				session.flush();
				return null;
			}
		});
	}

	public void evict(final Object entity) {
		this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				session.evict(entity);
				return null;
			}
		});
	}

	public void refresh(final Object entity) {
		this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				session.refresh(entity);
				return null;
			}
		});
	}

	public void flushAndClear() {
		this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				session.flush();
				session.clear();
				return null;
			}
		});
	}

	public List findAll() {
		return findAll(getModelClass());
	}

	public List findAll(Class clazz) {
		return this.getHibernateTemplate().loadAll(clazz);
	}

	public List findAll(String orderProperty, String orderType) {
		QueryHelper helper = new QueryHelper(getModelClass());
		helper.orderBy(orderProperty, orderType);

		return getList(helper);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.flink.prca.biz.dao.BaseDao#deleteById(java.io.Serializable)
	 */
	public void deleteById(Serializable id) {
		this.getHibernateTemplate().delete(this.findById(id));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.flink.prca.biz.dao.BaseDao#delete(java.lang.Object)
	 */
	public void delete(Object entity) {
		this.getHibernateTemplate().delete(entity);
	}

	public void deleteAll(Collection entities) {
		this.getHibernateTemplate().deleteAll(entities);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.flink.prca.persistence.dao.BaseDAO#saveOrUpdate(java.lang.Object)
	 */
	public void saveOrUpdate(Object entity) {
		this.getHibernateTemplate().saveOrUpdate(entity);
	}

	public void saveOrUpdateAll(Collection entities) {

		// 从源码看，hibernate
		// 的saveOrUpdateAll方法是针对每一个对象的保存/更新都开启和关闭事务，这对大量数据操作存在一定的效率问题.
		// 因此hibernate4删除了
		for (Object element : entities) {
			this.getHibernateTemplate().saveOrUpdate(element);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.flink.prca.persistence.dao.BaseDAO#save(java.lang.Object)
	 */
	public Serializable save(Object entity) {
		return this.getHibernateTemplate().save(entity);
	}

	public Serializable insert(Object entity) {
		return this.getHibernateTemplate().save(entity);
	}

	public Serializable save(Object entity, boolean flush, boolean clear) {
		Serializable pk = save(entity);

		if (flush) {
			flush();
		}

		if (clear) {
			clear();
		}

		return pk;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.flink.prca.persistence.dao.BaseDAO#update(java.lang.Object)
	 */
	public void update(Object entity) {
		this.getHibernateTemplate().update(entity);
	}

	public void merge(Object entity) {
		this.getHibernateTemplate().merge(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.flink.prca.persistence.dao.BaseDAO#findById(java.io.Serializable)
	 */
	public Object findById(Serializable id) {
		return findById(getModelClass(), id);
	}

	public Object findByIdWithLock(Serializable id) {
		return findByIdWithLock(getModelClass(),id);
	}

	public Object findByIdWithLock(Class model,Serializable id ) {
		if (id == null) {
			return null;
		}

		return getHibernateTemplate().get(model, id, LockMode.PESSIMISTIC_WRITE);//LockMode.UPGRADE
	}

	public Object findByIdWithLock(Serializable id, boolean wait) {
		return findByIdWithLock(getModelClass(),id,  wait);
	}

	public Object findByIdWithLock(Class model,Serializable id, boolean wait) {
		if (id == null) {
			return null;
		}

		LockMode mode = wait ? LockMode.PESSIMISTIC_WRITE : LockMode.UPGRADE_NOWAIT;//LockMode.UPGRADE

		return getHibernateTemplate().get(model, id, mode);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.flink.prca.persistence.dao.BaseDAO#findById(java.io.Serializable)
	 */
	public Object findById(Class model, Serializable id) {
		if (id == null) {
			return null;
		}

		return this.getHibernateTemplate().get(model, id);
	}

	/**
	 * description: 查询.
	 * 
	 * @param hql
	 * @param params
	 * @param paramTypes
	 * @return
	 * 
	 * @author aps-mhc
	 * @since 2007-12-03
	 * HibernateCallback 在4中全是泛型了
	 */
	protected List getList(final StringBuffer hql, final List params) {
		return this.getHibernateTemplate().execute(new HibernateCallback<List>() {
			public List doInHibernate(Session session) throws HibernateException {
				return session.createQuery(hql.toString()).setParameters(params.toArray(), getParamTypes(params))
						.list();
			}
		});
	}

	public int execute(final String hql) {
		return ((Integer) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				int count = session.createQuery(hql).executeUpdate();

				return Integer.valueOf(count);
			}
		})).intValue();
	}

	public int executeSql(final String sql) {
		return ((Integer) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				int count = session.createSQLQuery(sql).executeUpdate();

				return Integer.valueOf(count);
			}
		})).intValue();
	}

	protected int execute(final String hql, final Object param) {
		return ((Integer) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				int count = session.createQuery(hql).setParameter(0, param).executeUpdate();

				return Integer.valueOf(count);
			}
		})).intValue();
	}

	protected int execute(final String hql, final List params) {
		return ((Integer) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				int count = session.createQuery(hql).setParameters(params.toArray(), getParamTypes(params))
						.executeUpdate();

				return Integer.valueOf(count);
			}
		})).intValue();
	}

	protected int executeSql(final String sql, final Object param) {
		return ((Integer) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				int count = session.createSQLQuery(sql).setParameter(0, param).executeUpdate();

				return Integer.valueOf(count);
			}
		})).intValue();
	}

	protected int executeSql(final String sql, final Map param) {
		return ((Integer) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				SQLQuery sqlquery = session.createSQLQuery(sql);

				Iterator it = param.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry entry = (Map.Entry) it.next();
					String key = (String) entry.getKey();
					Object value = entry.getValue();
					sqlquery.setParameter(key, value);
				}
				int count = sqlquery.executeUpdate();

				return Integer.valueOf(count);
			}
		})).intValue();
	}

	protected int executeSql(final String sql, final List params) {
		return ((Integer) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				int count = session.createSQLQuery(sql).setParameters(params.toArray(), getParamTypes(params))
						.executeUpdate();

				return Integer.valueOf(count);
			}
		})).intValue();
	}

	/**
	 * 获取参数类型.
	 * 
	 * @param params
	 *            zhaomc 2013.11.25
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private static Type[] getParamTypes(List params) {
		List paramTypes = new ArrayList();

		for (Iterator i = params.iterator(); i.hasNext();) {
			Object param = (Object) i.next();
			// paramTypes.add(TypeFactory.heuristicType(param.getClass().getName()));//zhaomc
			// delete
			paramTypes.add(new TypeResolver().heuristicType(param.getClass().getName()));// zhaomc
																							// add
																							// 3.5以上
																							// 但是总
																							// new
		}

		return ArrayHelper.toTypeArray(paramTypes);
	}

	/**
	 * description: 查询.
	 * 
	 * @param hql
	 * @return
	 * 
	 * @author aps-mhc
	 * @since 2007-12-03
	 */
	protected List getList(final String hql) {
		return this.getHibernateTemplate().find(hql);
	}

	protected List getList(final String hql, Object param) {
		return this.getHibernateTemplate().find(hql, param);
	}

	/**
	 * description: 查询.
	 * 
	 * @param helper
	 * @return
	 * 
	 * @author aps-mhc
	 * @since 2007-12-03
	 */
	public List getList(final QueryHelper helper) {
		return this.getHibernateTemplate().execute(new HibernateCallback<List>() {
			public List doInHibernate(Session session) throws HibernateException {
				
				Query query = helper.createQuery(session);
				return query.list();
			}
		});
	}

	/**
	 * 加锁查询.
	 * 
	 * @param helper
	 * @param alias
	 * @param upgrade
	 * @return
	 */
	protected List getList(final QueryHelper helper, final String alias, final LockMode lockMode) {
		return this.getHibernateTemplate().execute(new HibernateCallback<List>() {
			public List doInHibernate(Session session) throws HibernateException {
				Query query = helper.createQuery(session);
				return query.setLockMode(alias, lockMode).list();
			}
		});
	}

	/**
	 * 加锁查询.
	 * 
	 * @param helper
	 * @param alias
	 * @param upgrade
	 * @return
	 */
	// aps-zmc 修改 增加.get(0)
	protected Object getUniqueResult(final QueryHelper helper, final String alias, final LockMode lockMode) {
		
		List list = this.getHibernateTemplate().execute(new HibernateCallback<List>() {
			public List doInHibernate(Session session) throws HibernateException {
				Query query = helper.createQuery(session);
				return query.setLockMode(alias, lockMode).list();
			}
		});
		if (list == null || list.isEmpty() || list.size() < 1) {
			return null;
		}
		return list.get(0);
	}

	/**
	 * description: 查询.
	 * 
	 * @param hql
	 * @param params
	 * @param paramTypes
	 * @return
	 * 
	 * @author aps-mhc
	 * @since 2007-12-03
	 */
	protected Object getUniqueResult(final StringBuffer hql, final List params) {
		return this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				return session.createQuery(hql.toString()).setParameters(params.toArray(), getParamTypes(params))
						.setMaxResults(1).uniqueResult();
			}
		});
	}

	/**
	 * description: 查询.
	 * 
	 * @param hql
	 * @param params
	 * @param paramTypes
	 * @return
	 * 
	 * @author aps-mhc
	 * @since 2007-12-03
	 */
	protected Object getUniqueResult(final QueryHelper helper) {
		return this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = helper.createQuery(session);
				return query.uniqueResult();
			}
		});
	}

	protected Object getUniqueResult(Class clazz, String property, Object value) {
		final QueryHelper helper = new QueryHelper(clazz);
		helper.append("where " + property + " = ?", value);
		return this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = helper.createQuery(session);
				return query.uniqueResult();
			}
		});
	}

	protected Object getUniqueResult(String property, Object value) {
		final QueryHelper helper = new QueryHelper(getModelClass());
		helper.append("where " + property + " = ?", value);
		return this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = helper.createQuery(session);
				return query.uniqueResult();
			}
		});
	}

	@SuppressWarnings("unchecked")
	protected Object getUniqueResult(final StringBuffer hql, Serializable param) {
		List params = new ArrayList();
		params.add(param);

		return getUniqueResult(hql, params);
	}

	/**
	 * description: 查询.
	 * 
	 * @param hql
	 * @return
	 * 
	 * @author aps-mhc
	 * @since 2007-12-03
	 */
	protected Object getUniqueResult(final String hql) {
		return this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				return session.createQuery(hql).setMaxResults(1).uniqueResult();
			}
		});
	}

	protected Object getUniqueResult(DetachedCriteria criteria) {
		List list = this.getHibernateTemplate().findByCriteria(criteria, 0, 1);

		return list.size() > 0 ? list.get(0) : null;
	}

	/**
	 * 获取一页数据.
	 * 
	 * @param hql
	 * @param page
	 * @return
	 */
	public PageResult getPageData(final String hql, final Page pager) {
		QueryHelper helper = new QueryHelper();
		helper.append(hql);

		return this.getPageData(helper, pager);
	}

	/**
	 * 获取一页数据.
	 * 
	 * @param helper
	 * @param page
	 * @return
	 */
	protected PageResult getPageData(final QueryHelper helper, final Page pager) {
		if (pager == null) {
			List list = getList(helper);
			int size = list.size();
			PageResult p = new PageResult(size, 1, size == 0 ? 1 : size);
			p.setData(list);

			return p;
		} else {
			return this.getPageData(helper, pager.getPageNumber(), pager.getPageSize());
		}
	}



//	/**
//	 * 获取一页数据.
//	 * 
//	 * @param helper
//	 * @param page
//	 * @return
//	 */
//	protected Paginater getPageData(final String hql, final long pageNumber, final int pageSize) {
//		QueryHelper helper = new QueryHelper();
//		helper.append(hql);
//
//		return this.getPageData(helper, pageNumber, pageSize);
//	}

	/**
	 * 获取一页数据.
	 * 
	 * @param helper
	 * @param page
	 * @return
	 */
	protected PageResult getPageData(final QueryHelper helper,final int pageNumber, final int pageSize) {
		return (PageResult) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = helper.createQuery(session);
				ScrollableResults results = query.scroll();
				results.last();
				int totalCount = results.getRowNumber() + 1;// 设置总记录数

				PageResult paginater = new PageResult(totalCount, pageNumber, pageSize);
				query.setMaxResults(paginater.getPageSize());
				query.setFirstResult((int) paginater.getOffsetIndex());
				List list = query.list();
				paginater.setData(list);

				return paginater;
			}
		});
	}

	/**
	 * description: 查询.
	 * 
	 * @param helper
	 * @return
	 * 
	 * @author aps-mhc
	 * @since 2007-12-03
	 */
	public List getListBySql(final QueryHelper helper) {
		return (List) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = helper.createSQLQuery(session);
				
				return query.list();
			}
		});
	}

	public List getListBySql(final QueryHelper helper, final ResultTransformer transformer) {
		return (List) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = helper.createSQLQuery(session);
				query.setResultTransformer(transformer);
				return query.list();
			}
		});
	}

	public List getListBySql(final String sql) {
		return (List) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				QueryHelper helper = new QueryHelper();
				helper.append(sql);
				
				Query query = helper.createSQLQuery(session);
				return query.list();
			}
		});
	}

	/**
	 * description: 查询.
	 * 
	 * @param helper
	 * @return
	 * 
	 * @author aps-mhc
	 * @since 2007-12-03
	 */
	protected Object getUniqueResultBySql(final QueryHelper helper) {
		return this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = helper.createSQLQuery(session);
				return query.uniqueResult();
			}
		});
	}

	/**
	 * description: 查询.
	 * 
	 * @param helper
	 * @return
	 * 
	 * @author aps-mhc
	 * @since 2007-12-03
	 */
	protected Object getUniqueResultBySql(final String sql) {
		return this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				QueryHelper helper = new QueryHelper();
				helper.append(sql);
				Query query = helper.createSQLQuery(session);
				return query.uniqueResult();
			}
		});
	}

	/**
	 * 获取一页数据.
	 * 
	 * @param helper
	 * @param page
	 * @return
	 */
	public PageResult getPageDataBySql(final QueryHelper helper, final PageResult paginater) {
		return (PageResult) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = helper.createSQLQuery(session);
				query.setMaxResults(paginater.getPageSize());
				query.setFirstResult((int) paginater.getOffsetIndex());
				List list = query.list();
				paginater.setData(list);

				return paginater;
			}
		});
	}

	/**
	 * 获取一页数据.
	 * 
	 * @param helper
	 * @param page
	 * @return
	 */
	public PageResult getPageDataBySql(final QueryHelper helper, final Page pager) {
		return (PageResult) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {


				Query query = helper.createSQLQuery(session);
				ScrollableResults results = query.scroll();
				results.last();
				int totalCount = results.getRowNumber() + 1;// 设置总记录数
				query.setMaxResults(pager.getPageSize());
				query.setFirstResult((int) pager.getOffsetIndex());
				
				List list = query.list();

				PageResult paginater = new PageResult(totalCount, pager.getPageNumber(), pager
						.getPageSize());
				paginater.setData(list);

				return paginater;
			}
		});
	}

	/**
	 * 获取一页数据.
	 * 
	 * @param helper
	 * @param page
	 * @return
	 */
	public PageResult getPageDataBySql(final QueryHelper helper, final Page pager, final int recordCount) {
		return (PageResult) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = helper.createSQLQuery(session);
				query.setMaxResults(pager.getPageSize());
				query.setFirstResult((int) pager.getOffsetIndex());				
				List list = query.list();

				PageResult paginater = new PageResult(recordCount, pager.getPageNumber(), pager.getPageSize());
				paginater.setData(list);

				return paginater;
			}
		});
	}

	/**
	 * 获取一页数据.
	 * 
	 * @param helper
	 * @param page
	 * @return
	 */
	protected PageResult getPageDataBySql(final QueryHelper helper, final Page pager,
			final ResultTransformer transformer) {
		return (PageResult) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				if (pager == null) {
					List list = getListBySql(helper, transformer);
					int size = list.size();
					PageResult p = new PageResult(size, 1, size == 0 ? 1 : size);
					p.setData(list);

					return p;
				}
				Query query = helper.createSQLQuery(session);
				
				ScrollableResults results = query.scroll();
				results.last();
				int totalCount = results.getRowNumber() + 1;// 设置总记录数

				
				query.setMaxResults(pager.getPageSize());
				query.setFirstResult((int) pager.getOffsetIndex());	
				

				query.setResultTransformer(transformer);
				List list = query.list();

				PageResult paginater = new PageResult(totalCount, pager.getPageNumber(), pager
						.getPageSize());
				paginater.setData(list);

				return paginater;
			}
		});
	}

	/**
	 * 获取一页数据.
	 * 
	 * @param helper
	 * @param page
	 * @return
	 */
	protected PageResult getPageDataBySql(final QueryHelper helper, final Page pager,
			final ResultTransformer transformer, final int recordCount) {
		return (PageResult) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				if (pager == null) {
					List list = getListBySql(helper, transformer);
					int size = list.size();
					PageResult p = new PageResult(size, 1, size == 0 ? 1 : size);
					p.setData(list);

					return p;
				}
				Query query = helper.createSQLQuery(session);
				query.setMaxResults(pager.getPageSize());
				query.setFirstResult((int) pager.getOffsetIndex());	
				query.setResultTransformer(transformer);
				List list = query.list();

				PageResult paginater = new PageResult(recordCount, pager.getPageNumber(), pager.getPageSize());
				paginater.setData(list);

				return paginater;
			}
		});
	}

	// -------------------- HSQL ----------------------------------------------

	// 使用HSQL语句直接增加、更新、删除实体
	// update Order set counts=123 " Order是POJO类名，而counts是表的字段名，感觉有点奇怪
	// String
	// queryString="update from Yaoyueyingyue y set y.state='2' where y.yaoyueid in (?)";
	// getHibernateTemplate().bulkUpdate(queryString, updateIds.toArray());
	// 有人说 不在事务控制内了？update 在事务控制内
	// 但insert
	// UPDATE 和 DELETE语句的语法为： ( UPDATE | DELETE ) FROM? ClassName (WHERE
	// WHERE_CONDITIONS)?。
	public int bulkUpdate(String queryString) {
		return getHibernateTemplate().bulkUpdate(queryString);
	}

	// 使用带参数的HSQL语句增加、更新、删除实体
	public int bulkUpdate(String queryString, Object[] values) {
		return getHibernateTemplate().bulkUpdate(queryString, values);
	}

	// 陈捷增加的三个查询函数 可以根据object中的参数做匹配以及额外的hql做查询
	private static QueryHelper buildQueryHelper(Object object, String hqlPlus) throws Exception {
		QueryHelper helper = new QueryHelper();
		helper.append(" from " + object.getClass().getSimpleName() + " where 1=1 ");
		Field field[] = object.getClass().getDeclaredFields();
		for (Field f : field) {
			f.setAccessible(true);
			if (f.getType().isPrimitive() || f.getType().getPackage().getName().equals("java.lang")
					|| f.getType().getPackage().getName().equals("java.util")) {
				if (!f.getName().equals("serialVersionUID")) {
					StringBuffer sb = new StringBuffer();
					sb.append(f.get(object));
					String ss = sb.toString();
					if (!ss.equals("null")) {
						helper.append(" and " + f.getName() + " = ? ", f.get(object));
					}
				}
			}
		}
		if (!StringUtils.isEmpty(hqlPlus))
			helper.append(hqlPlus);
		return helper;
	}

	@SuppressWarnings("unchecked")
	public Object commonSingleQuery(Object object, String hqlPlus) throws Exception {
		QueryHelper helper = buildQueryHelper(object, hqlPlus);
		List list = this.getList(helper);
		if (list != null && list.size() > 0)
			return list.get(0);
		else
			return null;
	}

	@SuppressWarnings("unchecked")
	public List commonListQuery(Object object, String hqlPlus) throws Exception {
		QueryHelper helper = buildQueryHelper(object, hqlPlus);
		List list = this.getList(helper);
		return list;
	}

	public PageResult commonQuery(Object object, String hqlPlus, Page pager) throws Exception {
		QueryHelper helper = buildQueryHelper(object, hqlPlus);
		return this.getPageData(helper, pager);
	}

	public List select(Class myClass, String tableSuffix, String wherehql) throws Exception {
		DBAnnotation dbAnnotation = DBAnnotationManager.scanDBAnnotation(myClass);
		QueryHelper helper = new QueryHelper();

		// // where
		// StringBuffer wherehql = new StringBuffer();
		//
		// wherehql.append(" where  1=1 ");
		// if (whereMap != null)
		// {
		// Iterator it = whereMap.entrySet().iterator();
		// while (it.hasNext())
		// {
		//
		// Map.Entry entry = (Map.Entry) it.next();
		// String key = (String) entry.getKey();
		// Object value = entry.getValue();
		// wherehql.append(" and " + key + "=" + SqlUtil.getObjectValue(value));
		// }
		// }

		// select
		StringBuffer selecthql = new StringBuffer();
		selecthql.append("select ");
		// 主键
		Map<String, DBFieldAnnotation> keyMap = dbAnnotation.getKeyAnnotationMap();
		Iterator it = keyMap.entrySet().iterator();
		boolean bFirst = true;
		while (it.hasNext()) {

			Map.Entry entry = (Map.Entry) it.next();
			if (bFirst) {
				bFirst = false;
			} else {
				selecthql.append(" , ");
			}
			String key = (String) entry.getKey();
			DBFieldAnnotation dbFieldAnnotation = (DBFieldAnnotation) entry.getValue();
			//helper.appendScalar(key, TypeConvert.convert(dbFieldAnnotation.getReturnType().getName()));
			helper.appendScalar(key, dbFieldAnnotation.getReturnType());
			selecthql.append(dbFieldAnnotation.getDbField() + " " + key);
		}
		// 普通字段
		Map<String, DBFieldAnnotation> fieldMap = dbAnnotation.getFieldAnnotationMap();
		it = fieldMap.entrySet().iterator();
		while (it.hasNext()) {

			Map.Entry entry = (Map.Entry) it.next();
			if (bFirst) {
				bFirst = false;
			} else {
				selecthql.append(" , ");
			}
			String key = (String) entry.getKey();
			DBFieldAnnotation dbFieldAnnotation = (DBFieldAnnotation) entry.getValue();
			//helper.appendScalar(key, TypeConvert.convert(dbFieldAnnotation.getReturnType().getName()));
			helper.appendScalar(key, dbFieldAnnotation.getReturnType());
			selecthql.append(dbFieldAnnotation.getDbField() + " " + key);
		}
		selecthql.append(" from " + dbAnnotation.getTableName() + tableSuffix);
		helper.append(selecthql.toString());
		if (wherehql != null)
			helper.append(" " + wherehql.toString());
		List<Map> list = null;
		list = getListBySql(helper, Transformers.ALIAS_TO_ENTITY_MAP);
		logger.debug("查询数据成功");
		// list = getListBySql(helper, Transformers.aliasToBean(myClass));
		List beanList = AnnotationUtil.mapListToBeanList(myClass, list);
		return beanList;
	}

	// @SuppressWarnings("unused")
	// public void tableMapping(Map<String, Class<?>> tableMapping){
	// Assert.notEmpty(tableMapping , "The mapping parameter is empty!");
	// for (String tableName : tableMapping.keySet()) {
	// Class<?> entityClass = tableMapping.get(tableName);
	// String className = entityClass.getName();
	// ClassMetadata metadata =
	// this.getSessionFactory().getClassMetadata(className);
	// //Class<?> mappedClass = metadata.getMappedClass();
	// //mappedClass = ClassPoolUtils.tableMapping(className, tableName);
	// ClassPoolUtils.tableMapping(className, tableName);
	// }
	// }

	protected Serializable getKey(Serializable bean) {
		return null;
	}

	public void updateNotNullBean(Serializable bean) throws BizException {
		Serializable key = getKey(bean);
		if (key == null)
			throw new BizException("dao未设置主键");
		Object newBean = findById(key);
		CopyUtil.copyNotNullProperties(newBean, bean);
		update(newBean);

	}
}
